package com.example.testquery;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.nova.util.BaseActivity;
import com.lenovo.nova.util.Constant.Debug;
import com.lenovo.nova.util.StringUtil;
import com.lenovo.nova.util.debug.MyLog;
import com.lenovo.nova.util.debug.PerformanceRecorder;
import com.lenovo.nova.util.debug.slog;
import com.lenovo.nova.util.parse.DBParserUtil;
/**
 * DBParserUtil 的源码 可以通过 git clong https://code.csdn.net/scenic2009/tv_util.git
 * @author scenic
 */
@SuppressLint("NewApi")
public class MainActivity_new extends BaseActivity implements OnFocusChangeListener {
	private static String TAG = "MainActivity";
	private DBParserUtil util;
	private ProgressBar progress;
	private AutoCompleteTextView autoComple2;
	private SimpleCursorAdapter adapter2;
	private SimpleCursorAdapter mSimpleListAdapter;
	private static final int MSG_UPDATE_1 = 0;
	private static final int MSG_UPDATE_2 = 1;
	private static final int MSG_UPDATE_3 = 2;
	private long interval = 100;
	private ListView mList;
	private TextView mTxShowSearchCountInfo;
	private TextView mTxShowProgressInfo;
	private UpdateDialog mUpdatedialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		progress = (ProgressBar) findViewById(R.id.id_progressbar);
		mList = (ListView) findViewById(R.id.id_lst_showcontent);
		mTxShowSearchCountInfo = (TextView) findViewById(R.id.id_txview_showInfo);
		mTxShowProgressInfo = (TextView) findViewById(R.id.id_txview_show_progress_info);
		util = new DBParserUtil(this) {
			@Override
			protected Class onGetBeanForCreateTable() {
				return MyBean.class;
			}
		};

		int dbCount = util.getDBCount(MyBean.class);
		slog.p(TAG, "db count is " + dbCount);
		if (dbCount <= 0) {
			try {
				updateDatabase(107269,getAssets().open("data"));
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			findViewById(R.id.id_llayout_query_contaner).setVisibility(View.VISIBLE);
			Cursor cursor = util.getBeanListFromDB(MyBean.class, null, 0, 10);
			executeQuery(cursor, null, null);
		}
	}

	/**
	 * 
	 * @param allSize
	 * @param dataSrc  InputStream or  ArrayList<String>
	 */
	public void updateDatabase(int allSize,Object dataSrc) {
		progress.setMax(allSize);
		findViewById(R.id.id_rlayout_container).setVisibility(View.VISIBLE);
		progress.setVisibility(View.VISIBLE);
		findViewById(R.id.id_llayout_query_contaner).setVisibility(View.INVISIBLE);
		WirteDBTask task = new WirteDBTask();
		task.execute(dataSrc);
	}

	public void executeQuery(Cursor cursor1, Cursor cursor2, Cursor cursor3) {
		findViewById(R.id.id_rlayout_container).setVisibility(View.GONE);
		autoComple2 = (AutoCompleteTextView) findViewById(R.id.id_auto_finish_2);
		updateDate(cursor1, cursor2, cursor3);
		autoComple2.setAdapter(adapter2);
		initAutoCompleteView(autoComple2);
		autoComple2.addTextChangedListener(new MyTextWatcher(MSG_UPDATE_2));
		autoComple2.setOnItemClickListener(new MyOnItemClickListener(autoComple2));
	}

	private void initAutoCompleteView(AutoCompleteTextView view) {
		view.setThreshold(0);
		view.setOnFocusChangeListener(this);
	}
	
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		MyLog.p(Debug.METHOD_TAG, "onMenuOpened");
		
		if(mUpdatedialog == null){
			mUpdatedialog = new UpdateDialog();
		}
		slog.p("dialog visiable is  " + mUpdatedialog.isVisible());
		if(!mUpdatedialog.isVisible()){
			mUpdatedialog.show(getFragmentManager(), UpdateDialog.class.getName());
		}
		
		return super.onMenuOpened(featureId, menu);
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MyLog.p(Debug.METHOD_TAG, "onCreateOptionsMenu");
		return super.onCreateOptionsMenu(menu);
	}
	
	@SuppressLint("NewApi")
	private void updateDate(Cursor cursor1, Cursor cursor2, Cursor cursor3) {
		if (adapter2 == null ) {
			adapter2 = new SimpleCursorAdapter(this, R.layout.adapter_layout, cursor2, new String[] { "delivery_address" }, new int[] { R.id.id_txview_adapter }, 0);
		} else {
			if (cursor2 != null) {
				adapter2.swapCursor(cursor2);
			}
		}

	}

	class MyAdapter extends SimpleAdapter {
		public MyAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
		}
	}

	Handler mHander = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_UPDATE_1: {
				doCommon((Editable) msg.obj, msg.what);
			}
				break;
			case MSG_UPDATE_2: {
				doCommon((Editable) msg.obj, msg.what);
			}
				break;
			case MSG_UPDATE_3: {
				doCommon((Editable) msg.obj, msg.what);
			}
				break;
			}

		};
	};

	private Cursor doCommon(Editable s, int colomIndex) {
		slog.p(TAG, "doCommont " + s);

		String where = null;
		StringBuffer sb = new StringBuffer();

		Editable value2 = autoComple2.getText();
		switch (colomIndex) {
		case MSG_UPDATE_1:
			if (s != null) {
				sb.append("delivery_unit like '%" + s.toString() + "%'");
			}
			break;
		case MSG_UPDATE_2:
			value2 = null;
			if (s != null) {
				sb.append("delivery_address like '%" + s.toString() + "%'");
			}
			break;
		case MSG_UPDATE_3:
			if (s != null) {
				sb.append("road like '%" + s.toString() + "%'");
			}
			break;
		}

		if(sb.length() <= 0){
			sb.append("1=1");
		}
		
//		if (!StringUtil.isStringEmpty(value1)) {
//			sb.append(" and delivery_unit like " + "'%" + value1.toString() + "%'");
//		}
		if (!StringUtil.isStringEmpty(value2)) {
			sb.append(" and delivery_address like " + "'%" + value2.toString() + "%'");
		}
//		if (!StringUtil.isStringEmpty(value3)) {
//			sb.append(" and road like " + "'%" + value3.toString() + "%'");
//		}

		where = sb.toString();
		
		if(StringUtil.isStringEmpty(where)){
			where = "1=1 limit 0,10";
		}
		
		slog.p(TAG, "where is  " + where);
		Cursor cursor = util.getBeanListFromDBUseWhere(MyBean.class, null, where);
		slog.p(TAG, "cursor size is  " + cursor.getCount());
		switch (colomIndex) {
		case MSG_UPDATE_1: {
			updateDate(cursor, null, null);
		}
			break;
		case MSG_UPDATE_2: {
			updateDate(null, cursor, null);
		}
			break;
		case MSG_UPDATE_3: {
			updateDate(null, null, cursor);
		}
			break;
		}

		return cursor;
	}

	class MyTextWatcher implements TextWatcher {

		int msg;
		public MyTextWatcher(int msg) {
			this.msg = msg;
		}
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			
		}

		@Override
		public void afterTextChanged(Editable s) {
			sendMsg(s, msg);
		}
		
	}
	

	private void sendMsg(Editable s, int msgWhat) {
		mHander.removeMessages(msgWhat);
		Message msg = new Message();
		msg.what = msgWhat;
		msg.obj = s;
		mHander.sendMessageDelayed(msg, interval);
	}


	class WirteDBTask extends AsyncTask<Object, Integer, List> {
		@Override
		protected void onPostExecute(List result) {
			findViewById(R.id.id_llayout_query_contaner).setVisibility(View.VISIBLE);
			util.getBeanListFromDB(MyBean.class, null, 0, 0);
			Cursor cursor = util.getBeanListFromDB(MyBean.class, null, 0, 10);
			executeQuery(cursor, null, null);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			progress.setProgress(values[0]);
			if(mTxShowProgressInfo != null){
				mTxShowProgressInfo.setText("正在初始化数据库 共 " +progress.getMax() + "条 当前进度 " + values[0] );
			}
		}

		@Override
		protected void onPreExecute() {
			util.deleteAll(MyBean.class);
			super.onPreExecute();
		}
		
		public boolean savleToDB(String line,int index,List list,SQLiteDatabase db){
			String value[] = line.split(":");
			index++;
			if (value.length < 2) {
				Log.e("Error", "format error " + line + "  " + index);
				return false;
			}
			MyBean bean = new MyBean();
			bean.name1 = value[0];
			bean.name2 = value[1];
			bean.name3 = "none";
			list.add(bean);
			util.saveBean(bean, db);
			if (index % 500 == 0) {
				System.out.println("progress  " + index);
				publishProgress(index);
			}
			return true;
		}
		
		@Override
		protected List doInBackground(Object... params) {
			List<MyBean> list = new ArrayList<MyBean>();
			SQLiteDatabase db = util.getWritableDatabase();
			db.beginTransaction();
			if(params[0] instanceof InputStream){
				String line = null;
				try {
					InputStream input = (InputStream) params[0];
					BufferedReader br = new BufferedReader(new InputStreamReader(input));
					int index = 0;
					PerformanceRecorder rd = new PerformanceRecorder("saveDB");
					rd.start();
					while ((line = br.readLine()) != null) {
						savleToDB(line, index, list, db);
					}
					rd.end();
				} catch (Exception e) {
					e.printStackTrace();
					showAlertDialog("更新数据库错误，请检查数据文件的格式是否正确" + e.toString());
				}
			}else if(params[0] instanceof List){
				List lists = (List) params[0];
				for(int i = 0; i < lists.size() ;i++){
					String line = (String) lists.get(i);
					savleToDB(line, i, list, db);
				}
			}
			
			db.setTransactionSuccessful();
			db.endTransaction();
			
			return list;
		}

	}

	public void onClick(View view){
		switch(view.getId()){
		case R.id.id_btn_query:
			Editable query = autoComple2.getText();
			autoComple2.setDropDownAlwaysVisible(false);
			if(query != null){
				Cursor cursor = doCommon(query, MSG_UPDATE_2);
				slog.p(TAG, "onClick count is " + cursor.getCount());
				Toast.makeText(this, "当前匹配 " + cursor.getCount() + " 条", -1).show();
				mTxShowSearchCountInfo.setText("搜索到： " + cursor.getCount());
				if(cursor.getCount() > 0){
					if(mSimpleListAdapter == null){
						mSimpleListAdapter = new SimpleCursorAdapter(this, R.layout.adapter_list_view,
								cursor,
								new String[] {"delivery_unit","delivery_address"}, 
								new int[] {R.id.id_txview_adapter_1,R.id.id_txview_adapter_2},0);
						mList.setAdapter(mSimpleListAdapter);
					}else{
						mSimpleListAdapter.swapCursor(cursor);
					}
				}else{
					
				}
				
			}else{
				MyLog.e("Null");
			}
			break;
		}
	}
	
	class MyOnItemClickListener implements AdapterView.OnItemClickListener {
		AutoCompleteTextView autoComple;
		public MyOnItemClickListener(AutoCompleteTextView auto) {
			// TODO Auto-generated constructor stub
			autoComple = auto;
		}
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			onMyItemClick(autoComple, parent, view, position, id);
			if(autoComple.getText() != null){
				autoComple.setSelection(autoComple.getText().length());
			}
		}
		
		private void onMyItemClick(AutoCompleteTextView self, AdapterView<?> parent, View view, int position, long id) {
			TextView tx = (TextView) view.findViewById(R.id.id_txview_adapter);
			self.setText(tx.getText());
			self.setDropDownAlwaysVisible(false);
		}
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		final AutoCompleteTextView auto = (AutoCompleteTextView) v;
		if (hasFocus) {
			if (v == autoComple2) {
				sendMsg(null, MSG_UPDATE_2);
			}
			mHander.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					auto.showDropDown();
				}
			}, interval);
		}
		auto.setDropDownAlwaysVisible(hasFocus);
	}
}
